<?php

require_once('env_ini.php');


$version = $_GET['version'];
if(empty($version) || !is_numeric($version)) {
	Utils::ShowError(ErrorDefine::ILLEGALL_URI);
	return;
}

$resource = $_GET['resource'];
if(empty($resource)) {
	Utils::ShowError(ErrorDefine::ILLEGALL_URI);
	return;
}

$method = $_GET['method'];
if(empty($method)) {
	Utils::ShowError(ErrorDefine::ILLEGALL_URI);
	return;
}

$raw_post_data = file_get_contents('php://input'); 
$PostData = "";
$PostArray = array();
if(!empty($raw_post_data)) {
	$PostData = $raw_post_data;
	$CONTENT_TYPE = '';
	if (isset($_SERVER['CONTENT_TYPE'])) {
	    $CONTENT_TYPE = $_SERVER['CONTENT_TYPE'];
	}
	if (strpos(strtolower($CONTENT_TYPE),"text/xml")!==false){
	    //判断xml数据处理
	    $PostArray = Utils::XMLToArray($PostData);
	}else {
	    $PostArray = json_decode($PostData, true);//默认当成json处理
	}
	if(NULL === $PostArray) {
		if(strpos($PostData,'=') > 0)
		{
			parse_str($PostData, $PostArray);
		} else {
			Utils::ShowError(ErrorDefine::DATA_DECODE_FAILED);
			return;
		}
	}
	if(NULL === $PostArray) {
		Utils::ShowError(ErrorDefine::DATA_DECODE_FAILED);
		return;
	}
}

$fields = explode("_", $resource);
$resource = "";
foreach($fields as $field) {
	$resource .= ucfirst($field);
}

$fields = explode("_", $method);
$method = "";
foreach($fields as $field) {
	$method .= ucfirst($field);
}
$method .= "V".$version;

//for logging
$logParams = $_GET;
if(!empty($PostArray)) {
	$logParams = $PostArray;
}
$requestMethod = $_SERVER['REQUEST_METHOD'];

try
{
	$class = new ReflectionClass($resource);
	$instance = $class->newInstanceArgs();
	$function = $class->getmethod($method);
	
	$ret = $function->invoke($instance, $_GET, $PostArray);
	$status = $ret ? "Success" : "Failed";

	CLog::getInstance()->notice("Handle $requestMethod Request $status", 0, $logParams);
}
catch (ReflectionException $ex)
{
	CLog::getInstance()->notice("Catch ReflectionException: ".$ex->getMessage(), 0, $logParams);
	Utils::ShowError(ErrorDefine::ILLEGALL_URI);
	return;
}

?>
